package com.yc.cloud.portal.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.yc.cloud.security.utils.MemberUtils;
import lombok.val;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.time.LocalDateTime;

@MapperScan({"com.yc.cloud.mapper","com.yc.cloud.common.oss.mapper"})
@Configuration
@EnableTransactionManagement
//执行MetaObjectHandler的insertFill,updateFill需在Entity字段中标识,并且mybatis plus需指明 type-aliases-package值
public class MyBatisConfig implements MetaObjectHandler {


    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }


    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        val userId = getCreateBy(metaObject);
        this.setFieldValByName("createBy", userId, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        val userId = getUpdateBy(metaObject);
        this.setFieldValByName("updateBy", userId, metaObject);
    }

    private long getCreateBy(MetaObject metaObject) {
        val object = this.getFieldValByName("createBy", metaObject);
        long userId;
        if (object != null) {
            userId = (long) object;
        } else {
            userId = MemberUtils.getCurrentUseId();
        }
        return userId;
    }

    private long getUpdateBy(MetaObject metaObject) {
        val object = this.getFieldValByName("updateBy", metaObject);
        long userId;
        if (object != null) {
            userId = (long) object;
        } else {
            userId = MemberUtils.getCurrentUseId();
        }
        return userId;
    }
}
